package com.mac.intellect_flow.framework.security.filter;

import com.alibaba.fastjson2.JSONObject;
import com.mac.intellect_flow.except.ServiceException;
import com.mac.intellect_flow.framework.util.SecurityUtils;
import com.mac.intellect_flow.framework.util.TokenUtil;
import com.mac.intellect_flow.framework.model.LoginUser;
import com.mac.intellect_flow.reply.R;
import com.mac.intellect_flow.util.servlet.ServletUtils;
import com.mac.intellect_flow.util.web.WebFrameworkUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * token过滤器 验证token有效性
 * 
 * @author mac
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenUtil tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (Objects.nonNull(loginUser) && Objects.isNull(SecurityUtils.getAuthentication())) {
            try {
                tokenService.verifyToken(loginUser);
            } catch (ServiceException ex) {
                log.error("token认证失败ser:{}", ex);
                WebFrameworkUtils.renderString(response, JSONObject.toJSONString(R.error(ex.getCode(),ex.getMessage())));
                return;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }
}
